<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
                v-model="searchForm.title"
                placeholder="文章标题"
                clearable
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getArticleList">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getTagsList(); dialogAddVisible = true;">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="这是确定批量删除吗？" @confirm="delHandle(null)">
          <el-button type="danger" slot="reference" :disabled="delBtlStatu">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            border
            stripe
            @selection-change="handleSelectionChange">

      <el-table-column
              type="selection"
              width="55">
      </el-table-column>

      <el-table-column
              prop="title"
              label="标题"
              width="300">
      </el-table-column>
      <el-table-column
              prop="content"
              label="内容"
              :show-overflow-tooltip='true'
              width="500">
      </el-table-column>
      <el-table-column
              prop="tags"
              label="标签"
              show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tag style="margin: 5px" size="small" type="info" v-for="item in scope.row.tags">{{item.name}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
              prop="icon"
              label="操作"
              width="120"
              style=""
      >

        <template slot-scope="scope">

          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delHandle(scope.row.id)">
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>

        </template>
      </el-table-column>

    </el-table>


    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[5, 10, 20, 50]"
            :current-page="current"
            :page-size="size"
            :total="total">
    </el-pagination>


    <!--新增对话框-->
    <el-dialog
            title="新增文章"
            :visible.sync="dialogAddVisible"
            width="800px"
            :before-close="handleClose">

      <el-form :model="articleForm" :rules="articleFormRules" ref="articleForm" label-width="100px" class="demo-articleForm">

        <el-form-item label="标题" prop="title" label-width="100px">
          <el-input v-model="articleForm.title" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content" label-width="100px">
          <el-input v-model="articleForm.content" type="textarea" :rows="6"></el-input>
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-transfer
                  v-model="articleForm.valueBox"
                  :data="articleForm.data"
                  :titles="['待选标签', '已选标签']"
          ></el-transfer>.
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="isAdd = true; submitArticleForm('articleForm')">立即创建</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <el-dialog
            title="编辑文章"
            :visible.sync="permDialogVisible"
            width="800px"
            :before-close="handleClose">

      <el-form :model="articleForm" :rules="articleFormRules" ref="articleForm" label-width="100px" class="demo-articleForm">

        <el-form-item label="标题" prop="title" label-width="100px">
          <el-input v-model="articleForm.title" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content" label-width="100px">
          <el-input v-model="articleForm.content" type="textarea" :rows="6"></el-input>
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-transfer
                  v-model="articleForm.valueBox"
                  :data="articleForm.data"
                  :titles="['待选标签', '已选标签']"
          ></el-transfer>.
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="isAdd = false; submitArticleForm('articleForm')">更新文章</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>

<script>
  import qs from 'qs';
  export default {
    name: "Article",
    data() {
      return {
        searchForm: {
          title: ''
        },
        delBtlStatu: true,
        isAdd: true,

        total: 0,
        size: 10,
        current: 1,

        dialogAddVisible: false,
        articleForm: {
          id: null,
          title: '',
          content: '',
          valueBox: [],
          data: []
        },
        tableData: [],
        articleFormRules: {
          title: [
            {required: true, message: '请输入文章标题', trigger: 'blur'}
          ],
          content: [
            {required: true, message: '请输入内容', trigger: 'blur'}
          ]
        },

        multipleSelection: [],

        permDialogVisible: false,
        permForm: {},
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        permTreeData: []
      }
    },
    created() {
      this.getArticleList()
    },
    methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        console.log("勾选")
        console.log(val)
        this.multipleSelection = val;

        this.delBtlStatu = val.length === 0
      },

      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.size = val
        this.getArticleList()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.current = val
        this.getArticleList()
      },

      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.dialogAddVisible = false
        this.permDialogVisible = false
        this.articleForm = {
          id: null,
          title: '',
          content: '',
          valueBox: [],
          data: []
        }
      },
      handleClose() {
        this.resetForm('articleForm')
      },

      getArticleList() {
        this.$http.get("/zhengzhi/list", {
          params: {
            title: this.searchForm.title,
            current: this.current,
            size: this.size
          }
        }).then(res => {
          this.tableData = res.data.data.records
          this.size = res.data.data.size
          this.current = res.data.data.current
          this.total = res.data.data.total
        })
      },

      getTagsList() {
        this.articleForm.data = []
        this.$http.get('/tags/info').then(res => {
          let tags = res.data.data
          for(let i = 0; i < tags.length; i++) {
            this.articleForm.data.push({
              key: tags[i].id,
              label: tags[i].name
            })
          }
        })
      },

      submitArticleForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let tagList = this.articleForm.data.filter(item => this.articleForm.valueBox.indexOf(item.key) > -1);
            console.log(tagList)
            let tags = []
            tagList.forEach((value, index) => {
              tags.push({
                id: value.key,
                name: value.label
              })
            })

            let params = {
              title: this.articleForm.title,
              content: this.articleForm.content,
              tags: tags
            };

            if (!this.isAdd) {
              params['id'] = this.articleForm.id
            }

            this.$http.post(this.isAdd === true ? '/zhengzhi/save' : '/zhengzhi/update', params).then(res => {
              this.$message({
                showClose: true,
                message: '恭喜你，操作成功',
                type: 'success',
                onClose:() => {
                  this.getArticleList()
                }
              });
              this.resetForm(formName)
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      editHandle(id) {
        this.getTagsList()
        this.$http.get('/zhengzhi/info/' + id).then(res => {
          const data =  res.data.data
          this.articleForm.id = id
          this.articleForm.title = data.title
          this.articleForm.content = data.content
          this.articleForm.valueBox = data.tags.map(item => item.id)
          this.permDialogVisible = true
        })
      },
      delHandle(id) {

        var ids = []

        if (id) {
          ids.push(id)
        } else {
          this.multipleSelection.forEach(row => {
            ids.push(row.id)
          })
        }

        console.log(ids)

        this.$http.post("/zhengzhi/delete", ids).then(res => {
          this.$message({
            showClose: true,
            message: '恭喜你，操作成功',
            type: 'success',
            onClose:() => {
              this.getArticleList()
            }
          });
        })
      }
    }
  }
</script>

<style scoped>

  .el-pagination {
    float: right;
    margin-top: 22px;
  }

</style>
